package com.zj.processors.platform;

import com.zj.bean.TableColumnInfo;
import com.zj.bean.TableInfo;
import com.zj.job.CommonJob;
import com.zj.processors.BaseCommonProcessor;
import com.zj.util.DateUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.VelocityContext;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class PlatformFrontendProcessor extends BaseCommonProcessor {


    @Override
    public String getName() {
        return "platformFrontend";
    }

    @Override
    public String process(TableInfo tableInfo, CommonJob commonJob) {
        init(tableInfo, commonJob);
        try {
            createFiles();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ok";
    }

    private String getPackageName(String tableName) {

        if(tableName.contains("_")){
            tableName = tableName.substring(tableName.indexOf("_"), tableName.length());
        }
        tableName=tableName.replaceAll("_", "");
        return tableName.toLowerCase();
    }

    private void makedir(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists()) {
            file.mkdir();
        }
    }
    public String createFiles() throws Exception {

        String moduleName=getParam("moduleName");
        String baseDir=getParam("baseDir");
        String modelDesc=getParam("modelDesc");
        String routerName = this.lowFirstChar(this.convertDomainName(moduleName));
        log("moduleName ---- " + moduleName);
        log("routerName ----  " + routerName);
        log("baseDir ----  " + baseDir);

        String moduleDirPath = baseDir + "components/"+moduleName;
        makedir(moduleDirPath);

        VelocityContext context = new VelocityContext();
        String modelName=convertDomainName(tableInfo.getTableName());
        context.put("modelName", modelName);
        context.put("modelProperty", lowFirstChar(modelName));
        context.put("moduleName", moduleName);
        context.put("routerName", routerName);
        context.put("modelDesc", modelDesc);

        for (TableColumnInfo tableColumnInfo : tableInfo.getTableColumnInfoList()) {
            tableColumnInfo.setFieldName(lowFirstChar(convertDomainName(tableColumnInfo.getName())));
        }
        List<TableColumnInfo> tableColumnInfoList = new ArrayList<>();
        for(TableColumnInfo tableColumnInfo:tableInfo.getTableColumnInfoList()){
            if(tableColumnInfo.getName().equalsIgnoreCase("modify_time") || tableColumnInfo.getName().equalsIgnoreCase("update_time")
                    ||tableColumnInfo.getName().equalsIgnoreCase("update_date")
                    || tableColumnInfo.getName().equalsIgnoreCase("create_date")
                    || tableColumnInfo.getName().equalsIgnoreCase("create_time")
                    || tableColumnInfo.getName().equalsIgnoreCase("is_delete")
                    || tableColumnInfo.getName().equalsIgnoreCase("org_id")
                    || tableColumnInfo.getName().equalsIgnoreCase("id")){
                continue;
            }
            tableColumnInfoList.add(tableColumnInfo);
        }
        context.put("fieldList", tableColumnInfoList);

        File listFile = new File(moduleDirPath + "/" + modelName + "List.vue");
        if(!listFile.exists()){
            writeFile(context,"platform-fe-vm/ListPage.vm",listFile);
            log("new listFile ====== "+listFile.getName());
        }

        File formFile=new File(moduleDirPath +"/"+modelName+"Form.vue");
        if (!formFile.exists()) {
            writeFile(context,"platform-fe-vm/FormPage.vm",formFile);
            log("new formFile ====== " +formFile.getName());

        }
        String routerPath = baseDir + "router/modules/"+routerName+".js"  ;
        File file = new File(routerPath);
        if(!file.exists()){
            writeFile(context,"platform-fe-vm/routerjs.vm",routerPath);
            log("new routerFile ====== " +file.getName());
            addRouter(routerName,baseDir);
        }
        addPermission(moduleName,modelDesc);

        commonJob.log("task ok");
        return "ok";
    }

    private void addPermission(String moduleName,String modelDesc){
        try {
            Connection connection= DriverManager.getConnection(commonJob.getConfig().getSsoJdbcUrl(), commonJob.getConfig().getUserName(), commonJob.getConfig().getPassword());


            Integer parentId=checkAndInsert( 0,moduleName, modelDesc,connection);
            if (parentId == null) {
                return;
            }
            checkAndInsert(parentId, moduleName + "_add", "新增", connection);
            checkAndInsert(parentId, moduleName + "_delete", "删除", connection);
            checkAndInsert(parentId, moduleName + "_edit", "编辑", connection);
            checkAndInsert(parentId, moduleName + "_batch_delete", "批量删除", connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    private Integer checkAndInsert(Integer parentId,String moduleName,String modelDesc,Connection connection) throws SQLException {
        String sql="select id from sys_permission where app_id = 89 and url = '"+moduleName+"' and parent_id = "+parentId+";";

        ResultSet result=CommonJob.doQuery(sql,connection);
        while(result.next()) {
            return result.getInt("id");
        }
        String parentSql="INSERT INTO `sys_permission` (`app_id`, `parent_id`, `name`, `url`, `sort`, `is_menu`, `is_enable`, `is_delete`, `modify_time`, `org_id`, `icon`, `create_time`)\n" +
                "VALUES\n" +
                "\t( 89, "+parentId+", '"+modelDesc+"', '"+moduleName+"', NULL, NULL, 1, 0, NULL, NULL, NULL, '"+ DateUtil.getyyyy_MM_dd_hms(new Date())+"');";


        connection.createStatement().execute(parentSql);
        log("new permission ====== " +moduleName+"  " +modelDesc);


        ResultSet insertResult=CommonJob.doQuery(sql,connection);
        while(insertResult.next()) {
            int permissionId=insertResult.getInt("id");
            String authSql="INSERT INTO `sys_re_role_permission` ( `role_id`, `permission_id`, `app_id`, `is_delete`, `modify_time`, `org_id`, `create_time`)\n" +
                    "VALUES\n" +
                    "\t( 6, "+permissionId+", 89, 0, NULL, NULL, '"+ DateUtil.getyyyy_MM_dd_hms(new Date())+"');";
            connection.createStatement().execute(authSql);
            log("new auth ====== " +permissionId);

            return permissionId;
        }
        return null;
    }

    private void addRouter(String routerName,String baseDir){

        try {
            File routerIndexFile = new File(baseDir + "/router/index.js");
            List<String> codeList= FileUtils.readLines(routerIndexFile,"UTF-8");
            int offset=0;
            for(int i=0;i<codeList.size();i++){
                String codeLine=codeList.get(i);
                if(codeLine.contains("[")){
                    offset=i+1;
                }
            }
            codeList.add(offset,"        "+routerName+",");
            codeList.add(0,"import "+routerName+" from './modules/"+routerName+"'");
            FileUtils.writeLines(routerIndexFile,codeList);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
